package com.cn.wanxi.servlet.back;

import com.cn.wanxi.model.DataField;
import com.cn.wanxi.model.UserModel;
import com.cn.wanxi.service.IUserService;
import com.cn.wanxi.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/back/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.sendRedirect(DataField.LOCALHOST_PORT+"/html/back/login.html");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //用户登录
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        String code = (String) req.getSession().getAttribute("code");
        String codeipt = req.getParameter("codeipt");
        int result = 0;
        UserModel userModel = null;
        //如果验证码输入正确，则进行登录验证
        if (code.toLowerCase().equals(codeipt.toLowerCase())) {
            userModel = new UserModel();
            userModel.setUsername(req.getParameter("username"));
            userModel.setPassword(req.getParameter("password"));
            IUserService userService = new UserServiceImpl();
            userModel = userService.login(userModel);
            if (userModel!=null){
                result = 1;
                HttpSession session = req.getSession();
                session.setAttribute("username",userModel.getUsername());
            }
        }else //否则返回提示
            result = 2;
        resp.getWriter().println(result);
    }
}
